<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="medicineName">
        <el-input
          v-model="queryParams.medicineName"
          placeholder="请输入药品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="medicineList">
      <el-table-column label="药品名称" align="center" prop="medicineName" />
      <el-table-column label="药品剂量" align="center" prop="dosage" />
      <el-table-column label="药品介绍" align="center" prop="introduction" />
      <el-table-column label="库存数量" align="center" prop="quantity" />
      <el-table-column label="药品过期日期" align="center" prop="expirationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 新增过期情况列 -->
      <el-table-column label="过期情况" align="center">
        <template slot-scope="scope">
          <span :class="getExpirationClass(scope.row)">{{ getExpirationStatus(scope.row) }}</span>
        </template>
      </el-table-column>

      <!-- 新增库存情况列 -->
      <el-table-column label="库存情况" align="center">
        <template slot-scope="scope">
          <span :class="getStockClass(scope.row)">{{ getStockStatus(scope.row) }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>


<script>
import { listMedicine, getMedicine, delMedicine, addMedicine, updateMedicine } from "@/api/system/medicine";

export default {
  name: "Medicine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品信息表格数据
      medicineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        medicineName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
    };
  },
  created() {
    this.getList();
  },
  methods: {

    // 检查过期状态
    getExpirationStatus(drug) {
      const today = new Date();
      const expirationDate = new Date(drug.expirationDate);
      if (expirationDate < today) {
        return '已过期';
      } else if ((expirationDate - today) / (1000 * 60 * 60 * 24) <= 15) {
        return '即将过期';
      }
      return '未过期';
    },
    // 为过期情况设置颜色
    getExpirationClass(drug) {
      const status = this.getExpirationStatus(drug);
      if (status === '已过期') {
        return 'text-red'; // 红色
      } else if (status === '即将过期') {
        return 'text-orange'; // 橙色
      }
      return 'text-green'; // 绿色
    },
    // 检查库存状态
    getStockStatus(drug) {
      if (drug.quantity < 5) {
        return '库存低';
      } else if (drug.quantity < 10) {
        return '库存正常';
      }
      return '库存充足';
    },
    // 为库存情况设置颜色
    getStockClass(drug) {
      const status = this.getStockStatus(drug);
      if (status === '库存低') {
        return 'text-orange'; // 红色
      } else if (status === '库存正常') {
        return 'text-green'; // 橙色
      }
      return 'text-green'; // 绿色
    },
    // 假设有一个时间解析函数
    parseTime(time, format) {
      // 实现时间格式化逻辑
      const date = new Date(time);
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return format.replace('{y}', y).replace('{m}', m).replace('{d}', d);
    },


    /** 查询药品信息列表 */
    getList() {
      this.loading = true;
      listMedicine(this.queryParams).then(response => {
        this.medicineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        medicineName: null,
        dosage: null,
        introduction: null,
        quantity: null,
        expirationDate: null,
        storageCondition: null,
        batchNumber: null,
        manufacturer: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加药品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMedicine(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改药品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMedicine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMedicine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除药品信息编号为"' + ids + '"的数据项？').then(function() {
        return delMedicine(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/medicine/export', {
        ...this.queryParams
      }, `medicine_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.text-red {
  color: red;
}
.text-orange {
  color: orange;
}
.text-green {
  color: green;
}
</style>
